unit uActionAnimator;

interface
uses ExtCtrls, ActnList;
type
  TActionAnimator = class(TObject)
  private
    FCurrentImageIndex: Integer;
    FStartImageIndex: Integer;
    FStopImageIndex: Integer;
    FTimer: TTimer;
    FAction: TCustomAction;
    function GetAnimated: boolean;
    procedure SetAnimated(const Value: boolean);
    procedure SetAction(const Value: TCustomAction);
    procedure DoTimer(Sender: TObject);
  public
    constructor Create;
    destructor Destroy; override;
    procedure StartAnimation;
    procedure StopAnimation;
    property  Animated:boolean read GetAnimated write SetAnimated;
    property  Action:TCustomAction read FAction write SetAction;
    property  StartImageIndex:Integer read FStartImageIndex write FStartImageIndex default 0;
    property  StopImageIndex:Integer read FStopImageIndex write FStopImageIndex default 1;
  end;

implementation

{ TActionAnimator }

constructor TActionAnimator.Create;
begin
  Inherited;
  FTimer := TTimer.Create(nil);
  FTimer.Enabled := False;
  FTimer.Interval := 700;
end;

destructor TActionAnimator.Destroy;
begin
  FTimer.OnTimer := nil;
  FTimer.Enabled := false;
  FAction := nil;
  FTimer.Free;
end;

procedure TActionAnimator.DoTimer(Sender: TObject);
begin
  If FCurrentImageIndex = FStartImageIndex then
    FCurrentImageIndex := FStopImageIndex
  else
    FCurrentImageIndex := FStartImageIndex;
  if (Assigned(FAction) and (FAction.ImageIndex <> FCurrentImageIndex)) then
    FAction.ImageIndex := FCurrentImageIndex;
end;


function TActionAnimator.GetAnimated: boolean;
begin
  Result := FTimer.Enabled;
end;

procedure TActionAnimator.SetAction(const Value: TCustomAction);
begin
  FAction := Value;
end;

procedure TActionAnimator.SetAnimated(const Value: boolean);
begin
  if Value then
    StartAnimation
  else
    StopAnimation;
end;

procedure TActionAnimator.StartAnimation;
begin
  DoTimer(nil);
  FTimer.OnTimer := DoTimer;
  FTimer.Enabled:=true;
end;

procedure TActionAnimator.StopAnimation;
begin
  FTimer.OnTimer := nil;
  FTimer.Enabled := false;
  if (Assigned(FAction) and (FAction.ImageIndex <> FStartImageIndex)) then
    FAction.ImageIndex := FStartImageIndex;
end;

end.
 